from typing import Any, Optional
from pydantic import BaseModel
from sqlalchemy.orm import relationship
from sqlalchemy import Column, ForeignKey, String, DateTime
from sqlalchemy.sql import func
from .db import Base, engine, SessionLocal


class Project(BaseModel):
    token: str

    class Config:
        from_attributes = True


class ProjectDBModel(Base):
    __tablename__ = "projects"

    token = Column(String, unique=True, index=True, primary_key=True)
    states = relationship("StateDBModel", cascade="all,delete", backref="project")


class State(BaseModel):
    id: str
    timestamp: Any
    data: str
    parent_state: Optional[str]

    class Config:
        from_attributes = True


class StateDBModel(Base):
    __tablename__ = "states"

    id = Column(String, unique=True, index=True, primary_key=True)
    timestamp = Column(DateTime, server_default=func.now())
    data = Column(String)
    parent_state = Column(String, ForeignKey('states.id'), nullable=True)

    project_token = Column(String, ForeignKey("projects.token"))
    # project = relationship("ProjectDBModel", backref="state")


try:
    print("Creating table")
    Base.metadata.create_all(engine)
except Exception as ex:
    print(ex)
